import java.text.SimpleDateFormat;
import java.util.Date;


public class SimpleNotepad implements INotepad {
	
	private static final int DEFAULT_NUMBER_OF_PAGES = 10;
	private Page[] pages;
	
	public SimpleNotepad() {
		pages = new Page[DEFAULT_NUMBER_OF_PAGES];
	}

	/**
	 * 
	 * Adds text to a page.
	 * The page number is between 1 and DEFAULT_NUMBER_OF_PAGES.
	 * 
	 * @param pageNumber
	 * @param text
	 */
	@Override
	public void addTextToPage(int pageNumber, String text) {
		if ( text != null )
			if ( isCorrectPageNumber(pageNumber) ) {
				pageNumber--;
				
				createPageIfNotExists(pageNumber);
				
				pages[pageNumber].addText(text);
			}
	}

	/**
	 * @param pageNumber
	 * @return
	 */
	private boolean isCorrectPageNumber(int pageNumber) {
		return pageNumber >= 1 && pageNumber <= DEFAULT_NUMBER_OF_PAGES;
	}

	
	@Override
	public void replaceTextInPage(int pageNumber, String text) {
		if ( text != null && isCorrectPageNumber(pageNumber) ) {
			pageNumber--;
			createPageIfNotExists(pageNumber);
			
			pages[pageNumber].removeText();
			pages[pageNumber].addText(text);
		}
	}

	/**
	 * @param pageNumber
	 */
	private void createPageIfNotExists(int pageNumber) {
		//Lazy loading - allocates memory for page
		if ( pages[pageNumber] == null )
			pages[pageNumber] = new Page(new SimpleDateFormat().format(new Date()));
	}

	@Override
	public void removeText(int pageNumber) {
		if (isCorrectPageNumber(pageNumber) ) {
			createPageIfNotExists(pageNumber);
			pages[pageNumber-1].removeText();
		}
	}

	@Override
	public void printNotepad() {
		System.out.println(this.toString());
	}
	
	@Override
	public String toString() {
		String res = "";
		for (Page page : pages) {
			if ( page != null)
				res += page.getPageContents() + "\n";
		}
		return res;
	}
}
